def on_on_event():
    global uart_free
    serial.write_line(convert_to_text(pitch))
    serial.write_line(convert_to_text(roll + 400))
    serial.write_line(convert_to_text(yaw + 600))
    uart_free = True
control.on_event(4800, 4801, on_on_event)

def on_on_event2():
    global mapPitch, mapRoll, oled_free
    mapPitch = Math.constrain(pins.map(pitch, -90, 90, 1, 62), 1, 62)
    mapRoll = Math.constrain(pins.map(roll, -90, 90, 1, 126), 1, 126)
    OLED.clear()
    OLED.draw_line(0, mapPitch, 127, mapPitch)
    OLED.draw_line(mapRoll, 0, mapRoll, 63)
    basic.pause(100)
    oled_free = True
control.on_event(4800, 4803, on_on_event2)

def on_on_event3():
    global led_free
    if yaw < 45:
        basic.show_arrow(ArrowNames.NORTH)
    elif yaw < 90:
        basic.show_arrow(ArrowNames.NORTH_EAST)
    elif yaw < 135:
        basic.show_arrow(ArrowNames.EAST)
    elif yaw < 180:
        basic.show_arrow(ArrowNames.SOUTH_EAST)
    elif yaw < 225:
        basic.show_arrow(ArrowNames.SOUTH)
    elif yaw < 270:
        basic.show_arrow(ArrowNames.SOUTH_WEST)
    elif yaw < 315:
        basic.show_arrow(ArrowNames.WEST)
    else:
        basic.show_arrow(ArrowNames.NORTH_WEST)
    basic.pause(200)
    led_free = True
control.on_event(4800, 4802, on_on_event3)

def on_received_value(name, value):
    global pitch, roll, yaw, uart_free, led_free, oled_free
    if name == "pitch":
        pitch = value
    elif name == "roll":
        roll = value
    elif name == "yaw":
        yaw = value
        if uart_free:
            uart_free = False
            control.raise_event(4800, 4801)
        if led_free:
            led_free = False
            control.raise_event(4800, 4802)
        if oled_free:
            oled_free = False
            control.raise_event(4800, 4803)
radio.on_received_value(on_received_value)

mapRoll = 0
mapPitch = 0
yaw = 0
roll = 0
pitch = 0
oled_free = False
led_free = False
uart_free = False
uart_free = True
led_free = True
oled_free = True
OLED.init(128, 64)
OLED.clear()
OLED.write_string_new_line("pitch roll yaw")
OLED.write_string_new_line("Freda Li")
OLED.write_string_new_line("2023 4 14")
basic.pause(2000)
led.set_brightness(82)
radio.set_group(18)
serial.set_tx_buffer_size(4)